import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class DatabaseInitializer {

    private static final String JDBC_URL = "jdbc:mysql://192.168.1.17:3306/mybatis";
    private static final String USER = "root";
    private static final String PASSWORD = "Abc@1234.";

    public static void main(String[] args) {
        DatabaseInitializer initializer = new DatabaseInitializer();
        initializer.executeSqlScript("setup.sql");
    }

    public void executeSqlScript(String filePath) {
        try (Connection connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
             Statement statement = connection.createStatement();
             BufferedReader reader = new BufferedReader(new FileReader(filePath))) {

            StringBuilder sql = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sql.append(line).append("\\n");
            }

            // 使用分号分割SQL脚本为独立命令
            String[] sqlCommands = sql.toString().split(";");
            for (String command : sqlCommands) {
                command = command.trim();
                if (!command.isEmpty()) { // 避免执行空命令
                    statement.execute(command);
                }
            }

            System.out.println("SQL脚本执行成功。");

        } catch (SQLException e) {
            System.err.println("SQL错误: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("文件错误: " + e.getMessage());
        }
    }
}
